import { Table, Pagination, Button, Tag, InputNumber, Input, message } from 'antd'
import './class.scss'
import { useState, useRef, useEffect } from 'react'
import dialogue from '@/utils/Ai'
import { UserActions } from '@/store'
import { reqGetAllSchool, reqUploads } from '@/api/user'
import { useDispatch, useSelector } from 'react-redux'

function Class() {
  const dispatch: any = useDispatch()
  const [show, setShow] = useState(false)
  const limit = useSelector((state: any) => state.user.userInfo.authority)
  const [totalClass, setTotalClass] = useState(2)
  const [pageNO, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)
  const [output, setOutput] = useState<string>('')
  const [classInfo, setClassInfo] = useState([])
  const [like, setLike] = useState('')
  const [isEnd, setIsEnd] = useState(false)
  const [loading, setLoading] = useState(false)
  const [allClassInfo, setAllClassInfo] = useState([])
  const [classData, setClassData] = useState([])
  const ttsWSRef = useRef<WebSocket | null>(null)
  const totalResRef = useRef<string>('')
  const storeUserInfo = useSelector((state: any) => state.user.userInfo)

  const columns: any = [
    {
      title: '课程Id',
      width: 100,
      dataIndex: 'id',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '课程名',
      dataIndex: 'schoolName',
      align: 'center',
      ellipsis: true,
    },
  ]

  // 获取可以选的全部课程(分页)
  const getAllSchool = async () => {
    const res: any = await reqGetAllSchool({ pageSize, pageNO })
    if (res.code === 200) {
      const newRecords = res.data.records
        .map((item: any) => ({
          ...item,
          key: item.id,
        }))
        .sort((a: any, b: any) => a.id - b.id)
      setClassInfo(newRecords)
      setTotal(res.data.total)
    }
  }

  // 获取全部课程数据
  const getAllSchool2 = async () => {
    const res: any = await reqGetAllSchool({ pageNO: 1, pageSize: 10000000 })
    if (res.code === 200) {
      setAllClassInfo(res.data.records)
    }
  }

  useEffect(() => {
    getAllSchool()
  }, [pageNO, pageSize])

  useEffect(() => {
    Promise.all([getAllSchool2(), getUserInfo()])

    return () => {
      ttsWSRef.current?.close()
    }
  }, [])

  // 获取用户信息
  const getUserInfo = () => {
    dispatch(UserActions.getUserInfo())
  }

  // 存储大模型的回答
  const handleMessageReceived = () => {
    setOutput(totalResRef.current)
  }

  // 是否结束判断
  const endofJudgment = (data: boolean) => {
    setIsEnd(data)
  }

  // 分页器数据修改触发的回调
  const handleChange = (page: number, pageSize: number) => {
    setPageNo(page)
    setPageSize(pageSize)
  }

  useEffect(() => {
    if (isEnd) {
      setClassData(JSON.parse(output))
      setLoading(false)
      setShow(true)
    }
  }, [isEnd])

  // 开启智能选课
  const handleSelectClass = () => {
    if (like) {
      setShow(false)
      setLoading(true)
      const schoolClass = allClassInfo.map((record: any) => record.schoolName)
      const question: any = `${schoolClass}从中选${totalClass}门课，个人偏好为${like}，只要告诉我该选哪门课，不用说为什么，结果为["课程名1", "课程名2"]，引号为双引号, 数组长度为${totalClass}`
      dialogue(question, ttsWSRef, totalResRef, handleMessageReceived, endofJudgment)
      setLike('')
    } else {
      message.warning('偏好设置不能为空！')
    }
  }

  // 确定选择，上传数据
  const handleConfirm = async () => {
    const totalData = classData.map((item) => ({
      schoolName: item,
    }))

    const res: any = await reqUploads({ id: storeUserInfo.id, school: totalData })
    getUserInfo()
    setClassData([])
    setShow(false)
    if (res.code === 200) {
      message.success('选课数据上传成功！')
    } else {
      message.error('选课数据上传失败！')
    }
  }

  return (
    <div className="Class">
      {limit.choose === 1 ? (
        <div className="content">
          <div className="content-left">
            <div className="text">所有课程</div>
            <Table pagination={false} columns={columns} dataSource={classInfo}></Table>
            <Pagination
              style={{ marginTop: '20px' }}
              pageSizeOptions={['5', '10', '15', '20']}
              showSizeChanger
              defaultPageSize={pageSize}
              onChange={handleChange}
              total={total}
              align="end"
            />
          </div>
          <div className="content-right">
            <div className="content-right-top">
              <div className="mySchoolClass">
                <span>已选择的课程：</span>
                {storeUserInfo.school.length > 0 ? (
                  storeUserInfo.school.map((item: any, index: any) => (
                    <Tag key={index} color="processing">
                      {item.schoolName}
                    </Tag>
                  ))
                ) : (
                  <span>无</span>
                )}
              </div>
              <div className="ctp-main">
                <div style={{ marginRight: '20px' }}>
                  <span>偏好：</span>
                  <Input
                    value={like}
                    onKeyDown={(e) => {
                      e.key === 'Enter' && handleSelectClass()
                    }}
                    onChange={(e) => setLike(e.target.value)}
                    style={{ width: '100px' }}
                  />
                </div>
                <div style={{ marginRight: '20px' }}>
                  <span>选课数量：</span>
                  <InputNumber
                    min={1}
                    max={total}
                    defaultValue={2}
                    onChange={(val: any) => {
                      setTotalClass(val)
                    }}
                    changeOnWheel
                  />
                </div>
                <Button size="large" onClick={handleSelectClass} type="primary" ghost>
                  智能选课
                </Button>
              </div>
              {loading && (
                <div className="wrapper">
                  <div className="circle"></div>
                  <div className="circle"></div>
                  <div className="circle"></div>
                  <div className="shadow"></div>
                  <div className="shadow"></div>
                  <div className="shadow"></div>
                  <span>玩命加载中。。。</span>
                </div>
              )}
              {show && (
                <div className="select-content">
                  <p style={{ marginBottom: '20px' }}>已帮您选择课程：</p>
                  {classData.map((item, index) => (
                    <Tag className="tag" key={index} color="success">
                      {item}
                    </Tag>
                  ))}
                  <div style={{ marginTop: '10px' }}>
                    <Button size="large" onClick={handleConfirm}>
                      确定选择
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        <div style={{ marginTop: '35vh', fontSize: '30px', color: 'red', fontWeight: '600' }}>
          没有使用权限
        </div>
      )}
    </div>
  )
}

export default Class
